<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Home extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin: *');
    }
    public function test()
    {
        return $this->fetch('index/index');
    }
    /**
     * 获取about表数据：
     * type：1 关于我们  2 客服电话  3 隐私协议   4 派逊天地  5 平台换货地址  6 尺寸图  7 注册协议
     * @return string
     */
    public function login()
    {
        header('Access-Control-Allow-Origin: *');
        extract(input());
        if(isset($uuid) && $uuid){
            $res = Db::table('up_u_user')
                ->where('user_uuid',$uuid)
                ->find();
            if($res){
                $data = $this->getData($res['user_teacher']);
                $data['userInfo'] = $res;
                return json_encode(['status'=>200,'msg'=>$res,'data'=>$data]);
            }else{
                return json_encode(['status'=>100,'msg'=>'链接有误！']);
            }
        }
        $res = Db::table('up_u_user')
            ->where('user_name',$name)
            ->where('user_phone',$phone)
            ->find();
        if($res){
            $data = $this->getData($res['user_teacher']);
            $data['userInfo'] = $res;
            return json_encode(['status'=>200,'msg'=>$res,'data'=>$data]);
        }else{
            return json_encode(['status'=>100,'msg'=>'查无此人，请核实登录信息']);
        }

    }
    public function getData($teacher)
    {
        //第一页典礼开始视频
        $index_1 = Db::table('up_about')->where('id',1)->field('id,thumb,content')->find();
        //校领导介绍
        $leaders = Db::table('up_leader')->select();
        //班主任赠言
        $teacher_send = Db::table('up_send')
            ->where('type',1)->where('name',$teacher)
            ->field('id,name,thumb,content')
            ->find();
        //系科剪影
        $xi_video = Db::table('up_send')->where('type',2)->field('id,name,thumb,content')->select();
        //校长寄语
        $schoolmaster = Db::table('up_about')->where('id',3)->field('id,thumb,content')->find();
        //学生代表发言
        $student_top = Db::table('up_about')->where('id',4)->field('id,thumb,content')->find();
        //教师代表发言
        $teacher_top = Db::table('up_about')->where('id',5)->field('id,thumb,content')->find();
        //校园合影图
        $school_pic = Db::table('up_send')->where('type',3)->field('id,name,content')->select();
        $data = [
            'index_1' => $index_1,
            'leaders' => $leaders,
            'teacher_send' => $teacher_send,
            'xi_video' => $xi_video,
            'schoolmaster' => $schoolmaster,
            'student_top' => $student_top,
            'teacher_top' => $teacher_top,
            'school_pic' => $school_pic,
        ];
        return $data;

    }
    /**
     * 提交我的留言
     */
    public function myNote(){
        extract(input());
        $can = $this->minganci($mynote);
        if($can['conclusionType'] == 1){
            $res = Db::table('up_u_user')->where('user_id',$user_id)->update([
                'user_my_note' => $mynote,
                'updatetime' => date('Y-m-d H:i:s')
            ]);
            if($res){
                return json_encode(['status'=>200,'msg'=>'提交成功~']);
            }else{
                return json_encode(['status'=>100,'msg'=>'提交失败，请刷新重试~']);
            }
        }else{
            return json_encode(['status'=>100,'msg'=>'有不合规词汇，请审查之后再提交']);
        }


    }
    public function makeUserPhoto()
    {
        set_time_limit(0);
        header('Access-Control-Allow-Origin: *');
        if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            exit();
        }
        $userChoosePic = $_POST['userChoosePic'];
        $user_id = $_POST['user_id'];
        $baseres = base64_img($_POST['file'],true);
        $url =  http_type ();
        if($baseres['code'] == 200){
            //压缩图片
//            image_png_size_add ($baseres['new_file'] ,$baseres['new_file']);
//            return json(['status'=>200,'msg'=>"$url/{$newName}"]);
            $res = $this->getPepleFace($url . $baseres['msg']);
            if($res['code'] == 200){
                $two_to_one = $this->picToOne($userChoosePic,$url . $res['msg']);
                $endpic = $this->picLast($two_to_one);
                $res22 = Db::table('up_u_user')->where('user_id',$user_id)->setField('user_my_pic',$endpic);
                if($res22){
                    return json(['status'=>200,'msg'=>$endpic]);
                }else{
                    return json(['status'=>100,'msg'=>'生成失败，请刷新重试~']);
                }
            }else{
                return json(['status'=>100,'msg'=>'图片生成失败，请重试']);
            }

        }else{
            return json(['status'=>100,'msg'=>'解析错误，请刷新重试']);
        }
    }
    public function picToOne($srcurl,$desurl){
        //创建源图的实例
        $src = imagecreatefromstring(file_get_contents($srcurl));
        //创建点的实例
        $des = imagecreatefrompng($desurl);
        //获取点图片的宽高
        list($point_w, $point_h) = getimagesize($desurl);
        list($old_w, $old_h) = getimagesize($srcurl);
        //重点：png透明用这个函数
        // imagecopy($src, $des, 200, 0, 0, 0, $point_w, $point_h);
        $name = time() . rand(100000,999999) . '.png';
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images/' . $name;
        $height = 400;
        $beishu = $point_h/400;
        $width = $point_w/$beishu;
        $width_2  = $width/2;
        imagecopyresampled($src, $des, $old_w/2 - $width_2, $old_h-400, 0, 0, $width, $height, $point_w, $point_h);
        imagepng($src, $dir);
        imagedestroy($src);
        imagedestroy($des);
        $url =  http_type ();
        $result = $this->cutImg($url . '/uploads/images/' . $name,180,0,540,600);
        return $result;
    }
    public function picLast($srcurl){
        //目标图片路径
        $desurl = 'http://221.226.22.203:8080/shuju/zp_bj.png';
        //创建源图的实例
        $src = imagecreatefromstring(file_get_contents($srcurl));
        //创建点的实例
        $des = imagecreatefrompng($desurl);
        //获取点图片的宽高
        list($point_w, $point_h) = getimagesize($desurl);
        list($old_w, $old_h) = getimagesize($srcurl);
        $name = time() . rand(100000,999999) . '.png';
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images/' . $name;
        //重点：png透明用这个函数
        // imagecopy($src, $des, 200, 0, 0, 0, $point_w, $point_h);
        imagecopyresampled($src,$des,  0, 0, 0, 0, 540, 600, $point_w, $point_h);
        imagepng($src, $dir);
        imagedestroy($src);
        imagedestroy($des);
        $url =  http_type ();
        return $url . '/uploads/images/' . $name;
    }
    public function cutImg ($imgfile, $x=0, $y=0, $width = 100, $height= 100)
    {
//得到原图宽高

//打开原图资源
        $img = imagecreatefrompng($imgfile);
//创建切图资源
        $cut_img = imagecreatetruecolor($width, $height);
//切图
        imagecopyresampled($cut_img, $img, 0, 0, $x, $y, $width, $height, $width, $height);
//获取原图后缀
        $ext = pathinfo($imgfile, PATHINFO_EXTENSION);
//生成保存路径
        $name = time() . rand(100000,999999) . '.png';
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images/' . $name;
//保存图片
        imagepng($cut_img, $dir);
//销毁资源
        imagedestroy($img);
        imagedestroy($cut_img);

        $url =  http_type ();
        return $url . '/uploads/images/' . $name;
    }

    public function saveBiye()
    {
        set_time_limit(0);
        header('Access-Control-Allow-Origin: *');
        if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            exit();
        }
        $user_id = $_POST['user_id'];
        $url =  http_type ();
        $baseres = base64_img($_POST['file'],true);
        if($baseres['code'] == 200){
            //压缩图片
//            image_png_size_add ($baseres['new_file'] ,$baseres['new_file']);
            $user = Db::table('up_u_user')->where('user_id',$user_id)->find();
            $biyepic = $this->addPicAndWenzi($url . $baseres['msg'],$user);
            $res = Db::table('up_u_user')->where('user_id',$user_id)->setField('user_biye_pic',$biyepic);
            if($res){
                return json_encode(['status'=>200,'msg'=>$biyepic]);
            }else{
                return json_encode(['status'=>100,'msg'=>'提交失败，请刷新重试~']);
            }

        }else{
            return json_encode(['status'=>100,'msg'=>'转存失败，请刷新重试~']);
        }
    }
    public function addPicAndWenzi($qrodeimg,$user){
        //这是背景图片的url
        $bannerimg = 'http://221.226.22.203:8080/shuju/biye.png';
        //这是需要插入到背景图的图片url
        //这是要插入到图片的文字
        $name = $user['user_name'];
        $sex = $user['user_sex'];
        $y = substr($user['user_birthday'],0,4);
        $m = substr($user['user_birthday'],4,2);
        $d = substr($user['user_birthday'],6,2);

        $zhuanye = $user['user_zhuanye'];
        //创建画布
        $logo = imagecreatefromstring(file_get_contents($bannerimg));
        $head_img1 = imagecreatefromstring(file_get_contents($qrodeimg));
        //写入文字
        $black = imagecolorallocate($logo, 0, 0, 0);
        //写的文字用到的字体
        $font = ROOT_PATH . 'public' . DS . 'Alibaba-PuHuiTi-Regular.ttf';
        //在图片里插入文字($msg,$black,$grey)
        imagettftext($logo, 14, 0, 240, 340, $black,$font, $name);
        imagettftext($logo, 14, 0, 380, 340, $black,$font, $sex);
        imagettftext($logo, 14, 0, 435, 340, $black,$font, $y);
        imagettftext($logo, 14, 0, 540, 340, $black,$font, $m);
        imagettftext($logo, 14, 0, 600, 340, $black,$font, $d);
        imagettftext($logo, 14, 0, 450, 400, $black,$font, $zhuanye);
        imagecopyresampled($logo, $head_img1, 786, 90, 0, 0, 150, 170, imagesx($head_img1), imagesy($head_img1));
        //生成图片
        $name = time() . rand(100000,999999) . '.png';
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images/' . $name;
        imagepng($logo, $dir);
        $url =  http_type ();
        return $url . '/uploads/images/' . $name;
    }

    public function request_post($url = '', $param = '')
    {
        header('Access-Control-Allow-Origin: *');
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }
    public function getPepleFace($olddir)
    {
        header('Access-Control-Allow-Origin: *');
//        $url = 'https://aip.baidubce.com/oauth/2.0/token';
//        $post_data['grant_type']       = 'client_credentials';
//        $post_data['client_id']      = 'gWbA4nO1cPBG2PnkEqKL8Sqt';
//        $post_data['client_secret'] = 'oe2GhevvGdcIWI7eTL70iy03XzoW7dzQ';
//        $o = "";
//        foreach ( $post_data as $k => $v )
//        {
//            $o.= "$k=" . urlencode( $v ). "&" ;
//        }
//        $post_data = substr($o,0,-1);
//
//        $res = $this->request_post($url, $post_data);
//        $res = json_decode($res,true);
        $token = '24.fe203b9961229ee28a7ce5063689f992.2592000.1596888177.282335-21222087';
//        $token = $res['access_token'];
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=' . $token;
        $img = file_get_contents($olddir);
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img,
            'type' => 'foreground'
        );
        $res = $this->request_post($url, $bodys);
        $res = json_decode($res,true);
        if(isset($res['foreground'])){
            $res2 = base64_img('data:image/png;base64,' . $res['foreground'],true);
            return $res2;
        }else{
            return ['code' => 100 , 'msg' => '图片生成失败，请稍后重试~'];
        }

    }
    public function minganci($MessageContent){
        header('Access-Control-Allow-Origin: *');
//        $url = 'https://aip.baidubce.com/oauth/2.0/token';
//        $post_data['grant_type']       = 'client_credentials';
//        $post_data['client_id']      = '7wVqDAOEYtbQ63WbmGGEab8A';
//        $post_data['client_secret'] = 'XzkdYyRHPOSpxkTQgqwHy3ujY5ySGIAH';
//        $o = "";
//        foreach ( $post_data as $k => $v )
//        {
//            $o.= "$k=" . urlencode( $v ). "&" ;
//        }
//        $post_data = substr($o,0,-1);
//
//        $res = $this->request_post($url, $post_data);
//        $res = json_decode($res,true);
//        $token = $res['access_token'];
//        dump($token);die;
        $body = "text=$MessageContent";
        $header = array(
            'Accept:application/x-www-form-urlencoded',
            'Content-Type: application/x-www-form-urlencoded; charset=gbk'
        );
        $token = '24.c7ee9ed2f4254402670bc706e6732329.2592000.1597123477.282335-21270389';
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token;;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }
    public function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,50);
                imagedestroy($image);
                break;
            case 3:
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,50);
                imagedestroy($image);
                break;
        }
    }
}